package me.duyu.tools.handler


import io.vertx.core.AsyncResult
import io.vertx.ext.web.RoutingContext
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.DecodeException
import io.vertx.kotlin.coroutines.*
import kotlinx.coroutines.experimental.launch


fun submitInfo(context : RoutingContext)
{
    val res = context.response()
    val body = context.body;
    when(body){
        null -> {
            res.statusCode = 403
            res.end("The body is null!!!")
        }
        else -> {
            try {
                val json = JsonObject(body)
                val name = json.getString("name");
                json.put("ip", context.request().remoteAddress().host())
                val fsys = context.vertx().fileSystem();
                fsys.writeFile("./clients/$name", json.toBuffer()){
                    if(it.succeeded()){
                        res.statusCode = 200
                        res.end("succeeded");
                    } else {
                        res.statusCode = 403
                        res.end(it.toString());
                    }
                }

            } catch (e : DecodeException){
                res.statusCode = 403
                res.end(e.message)
            }
        }
    }
}

fun submitInfo2(context : RoutingContext)
{
    val res = context.response()
    val body = context.body;
    when(body){
        null -> {
            res.statusCode = 403
            res.end("The body is null!!!")
        }
        else -> {
            launch (context.vertx().dispatcher()){
                try {
                    val json = JsonObject(body)
                    val name = json.getString("name");
                    json.put("ip", context.request().remoteAddress().host())
                    val reply = awaitEvent<AsyncResult<Void>> {
                        context.vertx().fileSystem().writeFile("./clients/$name", json.toBuffer(), it);
                    }
                    if (reply.succeeded()) {
                        res.statusCode = 200
                        res.end("succeeded");
                    } else {
                        res.statusCode = 403
                        res.end(reply.toString());
                    }
                } catch (e : DecodeException){
                    res.statusCode = 403
                    res.end(e.message)
                }
            }
        }
    }
}